#!/usr/bin/env perl

use strict;
use warnings;

use File::Basename;

my $kompile = shift(@ARGV);
my $k_prelude = shift(@ARGV);
my $values = shift(@ARGV);
my $temp_prelude = "k-prelude.maude";

# create temp prelude
local $_ = get_file_content($k_prelude);


# remove imports
s/load.*?\n//sg;

# add imports in reversed order
s/^/\nload $values\n\n/;
my $path = dirname($k_prelude);
s/^/\nload $path\/k-model-checker.maude/;
s/^/\nload $path\/TCPSupport.maude/;
s/^/\nload $path\/socket.maude/;
s/^/\nload $path\/pl-builtins.maude/;


# save temp prelude
open FILE, ">", $temp_prelude or die "Cannot create prelude file. Error during automatic compilation!\n";
print FILE;
close FILE;


# kompile
$_ = `$kompile @ARGV -prelude $temp_prelude`;

# print kompile result
print;


# utils
sub get_file_content
{
    my $filename = shift;
    
    open FILEHANDLE, "<", $filename or die "Could not open $filename:\n$!";
    my @input = <FILEHANDLE>;
    close FILEHANDLE;
    
    return join("", @input);
}